﻿using System;
using RpcClient;
using RpcHelper;
using RpcModel;
using Wedonek.RpcStore.Gateway.Interface;
using Wedonek.RpcStore.Gateway.Model;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Gateway.Service
{
    internal class ContainerService : IContainerService
    {
        private readonly IContainerCollect _Container;
        private readonly IServerCollect _Server;
        private readonly IServerTypeCollect _ServerType = null;
        public ContainerService(IContainerCollect container,
                IServerTypeCollect serverType,
                IServerCollect server)
        {
            this._ServerType = serverType;
            this._Server = server;
            this._Container = container;
        }
        public ContainerDatum Get(Guid id)
        {
            return this._Container.Get(id);
        }
        public ContainerServer[] Query(QueryContainerParam query, IBasicPage paging, out long count)
        {
            QueryServiceParam q = query.ConvertMap<QueryContainerParam, QueryServiceParam>();
            q.IsContainer = true;
            ServerConfigDatum[] servers = this._Server.Query(q, paging, out count);
            if (servers.Length == 0)
            {
                return Array.Empty<ContainerServer>();
            }
            BasicContainer[] list = this._Container.Gets(servers.ConvertAll(a => a.ContainerId.Value));
            ServerType[] types = this._ServerType.Gets(servers.ConvertAll(c => c.SystemType));
            return servers.ConvertMap<ServerConfigDatum, ContainerServer>((a, b) =>
            {
                BasicContainer container = list.Find(c => c.Id == a.ContainerId.Value);
                ServerType type = types.Find(c => c.Id == a.SystemType);
                b.SystemName = type.SystemName;
                b.BalancedType = type.BalancedType.ToString();
                b.ContrainerId = container.ContrainerId;
                b.ContainerType = container.ContainerType;
                b.Remark = container.Remark;
                return b;
            });
        }

        public void SetRemark(Guid id, string remark)
        {
            ContainerDatum datum = this._Container.Get(id);
            if (datum.Remark == remark)
            {
                return;
            }
            this._Container.SetRemark(id, remark);
        }
    }
}
